package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetMealService;
import com.itheima.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.UUID;

/**
 * @author ：hg
 * @date ：Created in 2021-12-6 22:39
 * @description：体检套餐管理
 */
@RestController
@RequestMapping("/setmeal")
public class SetMealController {

    /**
     * 注入服务
     */
    @Reference
    private SetMealService setMealService;

    /**
     * 操作redis服务
     */
    @Autowired
    private JedisPool jedisPool;

    /**
     * 七牛云上传图片
     * @param imgFile
     * @return
     */
    @RequestMapping("/upload")
    public Result upload(@RequestParam("imgFile") MultipartFile imgFile) {
        // System.out.println(imgFile);
        //获取原始文件名
        String originalFilename = imgFile.getOriginalFilename();
        //截取后缀位置
        int index = originalFilename.lastIndexOf(".");
        //获取图片名后缀
        String extention = originalFilename.substring(index - 1);
        //拼接
        String fileName = UUID.randomUUID().toString() + extention;
        try {
            //七牛云上传
            QiniuUtils.upload2Qiniu(imgFile.getBytes(), fileName);
            //把图片的名称保存带redis中去
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,fileName);
        } catch (IOException e) {
            e.printStackTrace();
            //失败
            return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
        }
        //成功
        return new Result(true,MessageConstant.PIC_UPLOAD_SUCCESS,fileName);
    }

    /**
     * 新增套餐
     * @param setmeal
     * @param checkgroupIds
     * @return
     */
    @RequestMapping("/add")
    public Result add(@RequestBody Setmeal setmeal, Integer[] checkgroupIds) {

        try {
            setMealService.add(setmeal,checkgroupIds);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.ADD_SETMEAL_FAIL);
        }
        return new Result(true,MessageConstant.ADD_SETMEAL_SUCCESS);


    }

    /**
     * 分页查询
     * @param queryPageBean
     * @return
     */
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        return setMealService.pageQuery(queryPageBean);
    }



}
